package com.atguigu.spzx.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.mapper.SysUserMapper;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * ClassName: SysUserServiceImpl
 * Package: com.atguigu.spzx.service.impl
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2024-01-18
 * Time: 20:24
 */

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {

        //获取提交的用户名
        String userName = loginDto.getUserName();

        //根据用户名 查询用户表
        SysUser sysUser = sysUserMapper.selectByName(userName);
        //查不到 不存在
        if (sysUser == null) {
            throw new RuntimeException("用户名不存在");
        }

        //查到了 用户存在  比对密码
        String dbPwd = sysUser.getPassword();
        String dtoPwd = loginDto.getPassword();
        //输入的密码加密之后在比较
        dtoPwd = DigestUtils.md5DigestAsHex(dtoPwd.getBytes());

        //密码一致 登录成功 不一致登录失败
        if (!dtoPwd.equals(dbPwd)) {
            throw new RuntimeException("密码不正确");
        }

        //登录生成 生成一个用户的唯一标识 token
        String token = UUID.randomUUID().toString().replace("-", "");

        //把用户登录的用户信息 放大Redis中
        //key: token  val: 用户信息  超时时间和日期  用使用到JSON工具 将对象转为JSON字符串
        redisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);

        //返回loginVo对应
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);


        return loginVo;
    }
}
